<!-- 文章管理 -->
<template>
    <div>
        <el-row type="flex">
            <el-col :xs="24" :md="12">
                <el-row :gutter="10">
                    <el-col :xs="24" :md="12" :lg="6">
                        <el-input v-model="searchKey" placeholder="请输入文章标题" clearable></el-input>
                    </el-col>
                    <el-col :xs="24" :md="12" :lg="6">
                        <el-select v-model="articleState" placeholder="文章状态" clearable>
                            <el-option v-for="item in articleStateList" :key="item.id" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-col>
                </el-row>
            </el-col>
            <el-col :xs="24" :md="12">
                <el-row justify="end" align="middle">
                    <el-button type="primary" v-auth="'client:article:query'" @click="getTableData">查询</el-button>
                    <el-button type="primary" v-auth="'client:article:add'" @click="operateClick('add')">新增</el-button>
                </el-row>
            </el-col>
        </el-row>
        <el-divider class="margin-top-down"></el-divider>
        <el-table 
        :data="tableData" 
        border 
        width="100%"
        :height="tableHeight" 
        stripe
        v-loading="tableLoading">
            <el-table-column type="index" label="编号" header-align="center" align="center" min-width="50"></el-table-column>
            <el-table-column label="博文标题" prop="articleTitle" show-overflow-tooltip header-align="center" align="center" min-width="100"></el-table-column>
            <el-table-column label="博文作者" prop="articleAuthor" show-overflow-tooltip header-align="center" align="center" min-width="100"></el-table-column>
            <el-table-column label="博文类型" prop="sortName" header-align="center" align="center" min-width="100"></el-table-column>
            <el-table-column label="是否火热" prop="isHot" header-align="center" align="center" min-width="100">
                <template #default="scope">
                    <el-tag type="success" v-if="scope.row.isHot">是</el-tag>
                    <el-tag type="danger" v-else>否</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="是否推荐" v-auth="'client:article:add'" prop="isRecommend" header-align="center" align="center" min-width="100">
                <template #default="scope">
                    <el-switch v-model="scope.row.isRecommend" :disabled="scope.row.status != ARTICLE_STATUS.RELEASE_STATE.value" @change="(val)=>{switchChange(val, scope.row, '推荐', 'isRecommend')}"/>
                </template>
            </el-table-column>
            <el-table-column label="是否置顶" v-auth="'client:article:add'" prop="isTop" header-align="center" align="center" min-width="100">
                <template #default="scope">
                    <el-switch v-model="scope.row.isTop" :disabled="scope.row.status != ARTICLE_STATUS.RELEASE_STATE.value" @change="(val)=>{switchChange(val, scope.row, '置顶', 'isTop')}"/>
                </template>
            </el-table-column>
            <el-table-column label="浏览人数" prop="viewsCount" header-align="center" align="center" min-width="100"></el-table-column>
            <el-table-column label="评论数"   prop="commentsCount" header-align="center" align="center" min-width="100"></el-table-column>
            <el-table-column label="发布状态" prop="status" header-align="center" align="center" min-width="100">
                <template #default="scope">
                    <template v-for="item in statusList">
                        <el-tag :type="item.type" :key="item.value" v-if="scope.row.status === item.value">{{ item.desc }}</el-tag>
                    </template>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createdAt" show-overflow-tooltip header-align="center" align="center" min-width="100" :formatter="setFormatter"></el-table-column>
            <el-table-column label="更新时间" prop="updatedAt" show-overflow-tooltip header-align="center" align="center" min-width="100" :formatter="setFormatter"></el-table-column>
            <el-table-column label="操作" width="340" header-align="center" align="center" fixed="right">
                <template #default="scope">
                    <el-button type="info" plain @click="operateClick('view', scope.row)">查看</el-button>
                    <el-button type="warning" v-auth="'client:article:update'" v-if="scope.row.status==ARTICLE_STATUS.DRAFT_STATE.value" plain @click="operateClick('update', scope.row)">修改</el-button>
                    <el-button type="danger" v-auth="'client:article:delete'" plain @click="deleteClick(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row justify="end" class="public-margin-top">
            <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[20, 50, 100, 200]"
            :small="true"
            :disabled="false"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </el-row>
        <ArticleOperate 
        ref="articleOperateRef" 
        :listLength="listLength"
        @updateArticleList="getTableData"></ArticleOperate>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import ArticleOperate from './article-operate.vue';
import { articleApi } from '@/api/article/article/article-api';
import { setTableHeight } from '@/utils/tools-util';
import { formatTimeToStr } from '@/utils/date-util.js';
import { ElMessage, ElMessageBox } from 'element-plus'
import { ARTICLE_STATUS } from '@/constants/client/article';

// ========================= 实列挂载之前调用 =========================
onBeforeMount(() => {
    getTableData();
    setStatus();
});

// ========================= 实列挂载之后调用 =========================
onMounted(() => {
    tableHeight.value = setTableHeight();
});

// ========================= 计算属性 =========================
const listLength = computed(() => {
    return tableData.value.length;
});

// ========================= 监听窗口变化 =========================
let tableHeight = ref(0);
window.onresize = () => {
    tableHeight.value = setTableHeight();
};

let statusList = ref([]);
function setStatus() {
    for(let key in ARTICLE_STATUS) {
        statusList.value.push(ARTICLE_STATUS[key])
    };
    console.log(statusList)
};


// ========================= 表格 =========================
let searchKey = ref('');                    // 搜索值
let articleState = ref('');                 // 文章状态
const articleStateList = reactive([]);      // 状态列表
const tableData = ref([]);                  // 表格数据
let tableLoading = ref(false);              // 表格加载控制
// 数据查询
async function getTableData() {
    try {
        let conditions = {
            params: {
                articleTitle: searchKey.value,
                status: articleState.value
            },
            limit: pageSize.value,
            offset: currentPage.value,
            order:[['isTop', 'desc'], ['createdAt', 'desc']]
        };
        tableLoading.value = true;
        const res = await articleApi.list(conditions);
        if(res.meta.status !== 200) throw new Error(res.meta.msg);
        total.value = res.data.count;
        tableData.value = res.data.data;
        tableLoading.value = false;
    } catch (e) {
        console.error(e);
        ElMessage.error(e.message);
    } finally {
        tableLoading.value = false;
    };
};

// ========================= 分页 =========================
let currentPage = ref(1);
let pageSize = ref(20);
let total = ref(0);

function handleSizeChange(val) {
    pageSize.value = val;
    getTableData();
};

function handleCurrentChange(val) {
    currentPage.value = val;
    getTableData();
};

// ========================= 操作 =========================
// 数据新增
let articleOperateRef = ref();
function operateClick(type, row) {
    articleOperateRef.value.onShowDrawer(type, row);
};

// 修改推荐/置顶
function switchChange(val, row, text, field) {
    let confirmText = '';
    !val ? confirmText = '取消' : confirmText = '';
    ElMessageBox.confirm(
        `确定要${confirmText+text}当前博文吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info',
        }
    ).then(() => {
        articleOperateRef.value.switchUpdate(row);
    }).catch(() => {
        row[field] = !val;
    });
};

// 数据删除
function deleteClick(row) {
    ElMessageBox.confirm(
        '确定要删除当前博文吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        try {
            let params = {
                id: row.id
            };
            const res = await articleApi.delete(params);
            if(res.meta.status !== 200) throw new Error(res.meta.msg);
            ElMessage.success('删除成功');
            getTableData();
        } catch (e) {
            console.error(e);
            ElMessage.error(e.message);
        };
    });
};

// 格式化内容
function setFormatter(row, column, cellValue, inedx) {
    return formatTimeToStr(cellValue)
};
</script>

<style lang="scss" scoped>

</style>

